import com.zwc.kotlin.coroutines.delay
import kotlin.coroutines.*

fun main() {
    var list: List<Int> = emptyList()
    list += 0
    var coroutineContext: CoroutineContext = EmptyCoroutineContext
    coroutineContext += CoroutineName("co-01")
    coroutineContext += CoroutineExceptionHandler {

    }
    coroutineContext += LogInterceptor()
    val continuation = suspend {
        delay(1000)
        1
    }.createCoroutine(object : Continuation<Int> {
        override val context: CoroutineContext
            get() = coroutineContext

        override fun resumeWith(result: Result<Int>) {
            result.onFailure {
                context.get(CoroutineExceptionHandler)?.onError(it)
            }
            println(result)
        }

    })
    continuation.resume(Unit)
}

//协程名的实现
class CoroutineName(val name: String) : AbstractCoroutineContextElement(Key) {
    companion object Key : CoroutineContext.Key<CoroutineName>

}
//协程异常处理器的实现

class CoroutineExceptionHandler(val onErrorAction: (Throwable) -> Unit) : AbstractCoroutineContextElement(Key) {
    companion object Key : CoroutineContext.Key<CoroutineExceptionHandler>

    fun onError(error: Throwable) {
        error.printStackTrace()
        onErrorAction(error)
    }
}

class LogInterceptor() : ContinuationInterceptor {

    override val key = ContinuationInterceptor

    override fun <T> interceptContinuation(continuation: Continuation<T>) = LogContinuation(continuation)

}

class LogContinuation<T>(private val continuation: Continuation<T>) : Continuation<T> by continuation {
    override fun resumeWith(result: Result<T>) {
        println("before resumeWith: $result")
        continuation.resumeWith(result)
        println("after resumeWith.")
    }
}